var echarts = require('echarts');
import china from 'echarts/map/json/china.json';
echarts.registerMap('china', china);

import apiMixin from '@/mixin/apiMixin';
import uilts from '@/utils/index';

import HeadTotal from './component/headTotal/index.vue';


export default {
    mixins: [apiMixin],
    data() {
        return {
            loading: false,
            type:{
                index:0,
                list:['今日','昨日','前7天','前30天','累计'],//时间段名称
                left:['昨日','前日','上个周期','上个周期','上个周期'],//相互对于当前时段的上个周期
            },
            classOverIndex:0,//项目完成度的悬浮位置
            // 文字数据统计
            textTotal: '',
            // 今日数据统计
            todayTextTotal: '',
            tableData:[],
            // 缓存数据
            cacheData: {
                // 昨日
                'yesterday': null,
                // 前7天
                'frontSenDay': null,
                // 前30天
                'frontThirtDay': null,
            },
            dynamicData: {
                // 充值
                recharge: {
                    value: 0,
                    contrast: '+0%' 
                },
                withdraw: {
                    value: 0,
                    contrast: '+0%' 
                },
                earnings: {
                    value: 0,
                    contrast:  '+0%'
                },
                register: {
                    value: 0,
                    contrast:  '+0%'
                }
            },
            // 性别map对象
            sexMap: null,
            // 性别参数
            sexOptions: {
                title:{
                    text:"性别趋图",
                    left:-5,
                    textStyle:{
                        color:"#000",
                        fontSize:23,
                        fontWeight:300,
                        fontFamily:"microsoft yahei"
                    }
                },
                series: [
                    {
                        radius: ['45%', '65%'],
                        center: ['50%', '60%'],
                        type: 'pie',
                        itemStyle: {
                            normal: {
                                color: function(params) {
                                    //性别饼图
                                    var colorList = [
                                        new echarts.graphic.LinearGradient(0, 0, 0, 1,[{offset: 0, color: '#3cd3e9'},{offset: 0.2, color: '#68bdf0'},{offset: 1, color: '#a19df8'}]),
                                        new echarts.graphic.LinearGradient(0, 0, 0, 1,[{offset: 0, color: '#ffad96'},{offset: 0.2, color: '#fe7096'},{offset: 1, color: '#fe7096'}]),
                                        new echarts.graphic.LinearGradient(0, 0, 0, 1,[{offset: 0, color: '#5cdccb'},{offset: 0.2, color: '#66d1c5'},{offset: 1, color: '#66d1c5'}])
                                    ];
                                    return colorList[params.dataIndex]
                                }
                            }
                        },
                        labelLine: {
                            normal: {
                                show: true,
                                length: 15,
                                length2: 120,
                                lineStyle: {
                                color: '#d3d3d3'
                                },
                                align: 'right'
                            },
                            color: "#000",
                            emphasis: {
                                show: true
                            }
                        },
                        label: {
                            normal: {
                                formatter: function(params) {
                                    var str = '';
                                    let data = params.data;
                                    let radius = Number(data.radius);
                                    switch (params.name) {
                                        case '男性':
                                        str = '{a|}{nameStyle|男性 }' + '{rate|' + data.value + "人\n" + (radius.toFixed(2)=='NaN'?0:radius.toFixed(2)) + '%}';
                                        break;
                                        case '女性':
                                        str = '{b|}{nameStyle|女性 }' + '{rate|' + data.value + "人\n" + (radius.toFixed(2)=='NaN'?0:radius.toFixed(2)) + '%}';
                                        break;
                                        case '未知':
                                        str = '{c|}{nameStyle|未知 }' + '{rate|' + data.value + "人\n" + (radius.toFixed(2)=='NaN'?0:radius.toFixed(2)) + '%}';
                                        break;
                                    }
                                    return str
                                },
                                padding: [0, -110],
                                height: 165,
                                rich: {
                                    a: {
                                        width: 38,
                                        height: 38,
                                        lineHeight: 50,
                                        align: 'left',
                                    },
                                    b: {
                                        width: 29,
                                        height: 45,
                                        lineHeight: 50,
                                        align: 'left'
                                    },
                                    c: {
                                        width: 34,
                                        height: 33,
                                        lineHeight: 50,
                                        align: 'left'
                                    },
                                    nameStyle: {
                                        fontSize: 16,
                                        color: "#555",
                                        align: 'left'
                                    },
                                    rate: {
                                        fontSize: 16,
                                        color: "#1ab4b8",
                                        align: 'left'
                                    }
                                }
                            }
                        },
                        data: [],
                    },
                    {
                        radius: ['8%', '50%'],
                        center: ['50%', '60%'],
                        type: 'pie',
                        label: {normal: {show: false},emphasis: {show: false}},
                        labelLine: {normal: {show: false},emphasis: {show: false}},
                        animation: false,
                        tooltip: {show: false},
                        itemStyle: {normal: {color: 'rgba(250,250,250,0.5)'}},
                        data: [{value: 1,}],
                    }
                ]
            },
            // 充值提现map对象
            rechangKitMap: null,
            // 充值提现参数
            rechangKitOptions: {
                tooltip: {
                    trigger: 'axis',
                    backgroundColor:'rgba(255,255,255,1)',
                    borderColor:"#7B7DDC",
                    borderWidth:1,
                    padding:10,
                    textStyle:{
                        color:'#000',
                    }
                },
                legend: {
                    data: ['充值金额', '提现金额'],
                    textStyle: {
                    color: '#000'
                    },
                    top:'0%',
                    right:'0%'
                },
                grid:{
                    x:'0%',
                    width:'100%',
                    y:'18%',
                },
                xAxis: {
                    data: [],
                    axisLine: {
                        lineStyle: {
                        color: '#FFF'
                        }
                    },
                    axisLabel: {color: '#a3a3a3'},
                    axisTick:{
                    show:false,
                    },
                },
                yAxis: [{
                    splitLine: {show: false},
                    axisLine: {
                        lineStyle: {
                            color: '#FFF',
                        }
                    },
                    axisLabel:{
                        formatter:'{value} ',
                    }
                },
                {
                splitLine: {show: false},
                axisLine: {
                    lineStyle: {
                        color: '#000',
                    }
                },
                axisLabel:{
                    formatter:'{value} ',
                }
                }],
                series: [
                    {
                        name: '提现金额',
                        type: 'bar',
                        barWidth: 10,
                        itemStyle: {
                            normal: {
                                barBorderRadius: 5,
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1,[
                                {offset: 0, color: '#ff92a1'},{offset: 1, color: '#ff788a'}
                                ])
                            }
                        },
                        data: []
                    },
                    {
                        name: '充值金额',
                        type: 'bar',
                        barGap: '100%',
                        barWidth: 10,
                        itemStyle: {
                            normal: {
                                barBorderRadius: 5,
                                color: new echarts.graphic.LinearGradient(
                                    0, 0, 0, 1,
                                    [
                                        {offset: 0, color: '#f9cdad'},
                                        {offset: 1, color: '#ffae73'}
                                    ]
                                )
                            }
                        },
                        data: []
                    },
                ]
            },
            // 用户分布map对象
            userEarthMap: null,
            // 用户分布参数
            userEarthOptions: {
                title:{
                    text:"今日用户分布",
                    left:-5,
                    textStyle:{
                        color:"#000",
                        fontSize:23,
                        fontWeight:300,
                        fontFamily:"microsoft yahei"
                    }
                },
                tooltip: {
                    show: true,
                    formatter: function(params) {
                        return params.name + '：' + params.data['value'] + '人，占比' + (params.data['radius']=='NaN'?0:params.data['radius']) + '%'
                    },
                },
                visualMap: {
                    type: 'continuous',
                    orient: 'horizontal',
                    symbolSize:20,
                    itemWidth: 10,
                    itemHeight: 80,
                    text: ['多', '少'],
                    showLabel: true,
                    dimension: 0, seriesIndex: 0,
                    seriesIndex: [0],
                    min:0,
                    max:0,
                    inRange: {
                        color: [
                            'rgba(158, 207, 102,0.2)',
                            'rgba(158, 207, 102,0.4)',
                            'rgba(158, 207, 102,0.6)',
                            'rgba(158, 207, 102,0.8)', 
                            'rgba(158, 207, 102,1)'
                        ]
                    },
                    textStyle: {color: '#7B93A7'},
                    bottom: 30,
                    left: 'left',
                },
                geo: {
                    map: 'china',
                    label: {emphasis: {show: false}},
                    itemStyle: {
                        borderWidth:0,
                    },
                    emphasis: {
                        itemStyle: {
                            opacity:0.6,
                        },
                        opacity:0.6,
                    },
                    layoutCenter: ['50%', '55%'],
                    layoutSize:500
                },
                series: [{
                    name: 'mapSer',
                    type: 'map',
                    roam: false,
                    geoIndex: 0,
                    label: {show: false,},
                    data: []
                }]
            },
            // 发布任务金额map
            pushTaskPriceMap: null,
            // 发布任务金额参数
            pushTaskPriceOptions: {
                title:{
                    text:"发布任务金额",
                    left:-5,
                    textStyle:{
                        color:"#000",
                        fontSize:23,
                        fontWeight:300,
                        fontFamily:"microsoft yahei"
                    }
                },
                tooltip: {
                    show: true,
                    axisPointer: {
                        type: 'none'
                    },
                    trigger: 'axis',
                    backgroundColor:'rgba(255,255,255,1)',
                    borderColor:"#7B7DDC",
                    borderWidth:1,
                    padding:10,
                    textStyle:{
                        color:'#000',
                    }
                },
                grid: {top: '16%',left: '1.5%',right: '1.5%',bottom: '5%'},
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    axisLine: {show: false},
                    splitLine: {show: false},
                    axisTick: {
                        lineStyle: {color: '#bae0e8'},
                        inside:true
                    },
                    axisLabel: {
                        color: '#a3a3a3',
                    },
                    data: []
                },
                yAxis: [
                    {
                        axisLine: {show: false},
                        splitLine: {lineStyle: {color: '#bae0e8'}},
                        axisTick: {show: false},
                        type: 'value',
                        nameGap: '20',
                        position: 'left',
                        axisLabel: {
                            show:false
                        }
                    }
                ],
                series: [
                    {
                        name: '金额',
                        type: 'line',
                        smooth: 0,
                        showSymbol: false,
                        symbol: false,
                        lineStyle: {
                            normal: {
                                width: 2,
                                color: {
                                    type: 'linear',
                                    x: 0,
                                    y: 1,
                                    x2: 0,
                                    y2: 0,
                                    colorStops: [{offset: 0,color: '#68b7ff'},{offset: 1,color: '#1890ff'}],
                                    globalCoord: false
                                },
                                opacity: 0.2
                            }
                        },
                        areaStyle: {
                            normal: {
                                color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [{
                                    offset: 0.2,
                                    color: '#e6f7ff'
                                }, {
                                    offset: 1,
                                    color: '#1890ff'
                                }]),
                                opacity: 0.7
                            }
                        },
                        itemStyle: {
                            normal: {color: '#eb547c',borderColor: '#fff'},
                            emphasis: {color: '#eb547c',borderWidth: 6,borderColor: 'rgba(235,84,124,0.4)'}
                        },
                        data: []
                    }
                ]
            },
            // 发布任务分类map
            pushTaskSortMap: null,
            pushTaskSortOptions: {
                color: ['#00c2ff', '#f9cf67', '#e92b77'],
                title:{
                  text:"今日分类趋势",
                  left:-5,
                  textStyle:{
                    color:"#000",
                    fontSize:23,
                    fontWeight:300,
                    fontFamily:"microsoft yahei"
                  }
                },
                legend: {
                    show: true,
                    bottom: 0,
                    center: 0,
                    itemWidth: 14, // 图例标记的图形宽度。[ default: 25 ]
                    itemHeight: 14, // 图例标记的图形高度。[ default: 14 ]
                    itemGap: 21, // 图例每项之间的间隔。[ default: 10 ]横向布局时为水平间隔，纵向布局时为纵向间隔。
                    textStyle: {fontSize: 14,color: '#606266'},
                    data: ['今日'],
                },
                radar: [{
                    indicator: [
                        {text: '拼多多',max: 100},
                        {text: '短视频',max: 100},
                        {text: '微信',max: 100},
                        {text: '淘宝',max: 100},
                        {text: '京东',max: 100},
                        {text: '新浪',max: 100},
                        {text: '其它',max: 100}
                    ],
                    center: ['50%', '50%'],
                    radius: 142,
                    startAngle: 90,
                    splitNumber: 3,
                    orient: 'horizontal', // 图例列表的布局朝向,默认'horizontal'为横向,'vertical'为纵向.
                    name: {
                      formatter: '{value}',
                      textStyle: {
                        fontSize: 14, //外圈标签字体大小
                        color: '#a5a5a5' //外圈标签字体颜色
                      }
                    },
                    splitArea: { // 坐标轴在 grid 区域中的分隔区域，默认不显示。
                      show: true,
                      areaStyle: { // 分隔区域的样式设置。
                        color: ['#FFF'], // 分隔区域颜色。分隔区域会按数组中颜色的顺序依次循环设置颜色。默认是一个深浅的间隔色。
                      }
                    },
                    axisLine: { //指向外圈文本的分隔线样式
                      lineStyle: {
                        color: '#eee',
                        width: 1, // 分隔线线宽
                      }
                    },
                    splitLine: {
                      lineStyle: {
                        color: '#eee', // 分隔线颜色
                        width: 1, // 分隔线线宽
                      }
                    }
                },],
                series: [{
                    name: '雷达图',
                    type: 'radar',
                    itemStyle: {
                        emphasis: {
                            lineStyle: {
                            width: 4
                            }
                        }
                    },
                    data: [
                        {
                            name: '今日',
                            value: [0, 0, 0, 0, 0, 0, 0],
                            lineStyle:{color:"rgba(0,0,0,0)"},
                            areaStyle: {
                            normal: { // 单项区域填充样式
                                color: {
                                type: 'linear',
                                x: 0, //右
                                y: 0, //下
                                x2: 1, //左
                                y2: 1, //上
                                colorStops: [{
                                    offset: 0,
                                    color: '#e6f7ff'
                                },{
                                    offset: 1,
                                    color: '#1890ff'
                                }],
                                globalCoord: false
                                },
                                opacity: 0.6 // 区域透明度
                            }
                            },
                            symbolSize: 2.5, // 单个数据标记的大小，可以设置成诸如 10 这样单一的数字，也可以用数组分开表示宽和高，例如 [20, 10] 表示标记宽为20，高为10。
                            label: {                    // 单个拐点文本的样式设置                            
                            normal: {  
                                show: true,             // 单个拐点文本的样式设置。[ default: false ]
                                distance: 0,            // 距离图形元素的距离。当 position 为字符描述值（如 'top'、'insideRight'）时候有效。[ default: 5 ]
                                color: '#1890ff',          // 文字的颜色。如果设置为 'auto'，则为视觉映射得到的颜色，如系列色。[ default: "#fff" ]
                                fontSize: 9,           // 文字的字体大小
                                formatter:function(params) {  
                                    return params.value;  
                                }  
                            }  
                            },
                        },
                    ]
                }]
            },
            // 等待提现总额
            awiatMoneyTotal: 0,
            // 新用户行为标签列表
            newUserTagsList: [],
            // 老用户行为标签列表
            oldUserTagsList: [],
            // 充值金额相关
            investMoney: {
                weixin: 0,
                zfb: 0,
                admin: 0,
                total: 0
            },
            // 收益金额相关
            incomeMoney: {
                stick: 0,
                cashServiceFee: 0,
                platefromAmount: 0,
                total: 0,
            },
            // 支出金额相关
            expendMoneu: {
                invite: 0,
                beInvite:0,
                inviteRange: 0,
                commission: 0,
                taskRewarde: 0,
                scoreAmout: 0,
                total: 0
            },
            // 任务完成度列表
            taskCompleteList: [],
            // 任务完成金额
            taskCompletePriceTotal: 0

        }
    },
    mounted() {
        this.initMap();
        this.getRechangKitLately();
        //this.changeData('today');
        this.handleSpecData();
    },
    methods: {
        initMap() {
            // 赋值性别map对象
            this.sexMap = echarts.init(document.getElementById('sex'));
            // 充值提现map对象
            this.rechangKitMap = echarts.init(document.getElementById('columnar'));
            // 用户分布map对象
            this.userEarthMap = echarts.init(document.getElementById('earth'));
            // 发布任务金额map
            this.pushTaskPriceMap =  echarts.init(document.getElementById('push'));
            // 发布任务分类map
            this.pushTaskSortMap =  echarts.init(document.getElementById('radar'));

            let _self = this;
            window.onresize = function() {
                _self.sexMap.resize();
                _self.rechangKitMap.resize();
                _self.userEarthMap.resize();
                _self.pushTaskPriceMap.resize();
                _self.pushTaskSortMap.resize();
            }


            _self.rechangKitMap.setOption(_self.rechangKitOptions);
            _self.pushTaskPriceMap.setOption(_self.pushTaskPriceOptions);
            _self.sexMap.setOption(_self.sexOptions);
            _self.userEarthMap.setOption(_self.userEarthOptions);
            _self.pushTaskSortMap.setOption(_self.pushTaskSortOptions);
        },
        /**
         *  切换统计数据
         * @param { String } type 切换类型  
         */
        changeData(type) {
            let todayDate = new Date();
            let _self = this;
            var curName = '';
            const calculateDate = (diffDay) => {
                    // 毫秒数
                let prevMills = diffDay * 24 * 60 * 60 * 1000;
                let curMills = todayDate.getTime();
                return new Date(curMills - prevMills);
            };
            let slotObj = {
                'today': () => {
                    curName = '今日';
                    _self.type.index = 0;
                    let start =  uilts.Dateformat(todayDate,'yyyy-MM-dd');
                    let end =  uilts.Dateformat(todayDate,'yyyy-MM-dd');
                    _self.getStatisticsDataApi({
                        query_time: 'other',
                        start,
                        end
                    },(res)=>{
                        _self.parseData(res.this_vcation,res.analysis);
                    });
                },
                'yesterday': () => {
                    _self.type.index = 1;
                    if (_self.cacheData['yesterday']) {
                        _self.parseData(_self.cacheData['yesterday'].this_vcation,_self.cacheData['yesterday'].analysis);
                        return;
                    }
                    curName = '昨日';
                    let yesterday = calculateDate(1);
                    let start =  uilts.Dateformat(yesterday,'yyyy-MM-dd');
                    let end =  uilts.Dateformat(yesterday,'yyyy-MM-dd');
                    _self.getStatisticsDataApi({
                        query_time: 'other',
                        start,
                        end
                    },(res)=>{
                        _self.cacheData['yesterday'] = res;
                        _self.parseData(res.this_vcation,res.analysis);
                    });
                },
                // 前7天
                'frontSenDay': () => {
                    _self.type.index = 2;
                    if (_self.cacheData['frontSenDay']) {
                        _self.parseData(_self.cacheData['frontSenDay'].this_vcation,_self.cacheData['frontSenDay'].analysis);
                        return;
                    }
                    curName = '前7日';
                    let yesterday = calculateDate(1);
                    let startDay = calculateDate(7);
                    let start =  uilts.Dateformat(startDay,'yyyy-MM-dd');
                    let end =  uilts.Dateformat(yesterday,'yyyy-MM-dd');
                    _self.getStatisticsDataApi({
                        query_time: 'other',
                        start,
                        end
                    },(res)=>{
                        _self.cacheData['frontSenDay'] = res;
                        _self.parseData(res.this_vcation,res.analysis);
                    });
                },
                // 前30天
                'frontThirtDay': () => {
                    _self.type.index = 3;
                    if (_self.cacheData['frontThirtDay']) {
                        _self.parseData(_self.cacheData['frontThirtDay'].this_vcation,_self.cacheData['frontThirtDay'].analysis);
                        return;
                    }
                    curName = '前30日';
                    let yesterday = calculateDate(1);
                    let startDay = calculateDate(30);
                    let start =  uilts.Dateformat(startDay,'yyyy-MM-dd');
                    let end =  uilts.Dateformat(yesterday,'yyyy-MM-dd');
                    _self.getStatisticsDataApi({
                        query_time: 'other',
                        start,
                        end
                    },(res)=>{
                        _self.cacheData['frontThirtDay'] = res;
                        _self.parseData(res.this_vcation,res.analysis);
                    });
                },
                'all': () => {
                    curName = '累计';
                    _self.type.index = 4;
                    _self.getStatisticsDataApi({
                        query_time: 'all',
                    },(res)=>{
                        _self.parseData(res.this_vcation,res.analysis);
                    });
                }

            }
            slotObj[type]();
        },
        parseData (stayData,spec)  {
            let _self = this;
            console.log(stayData);
            const parseSingle = (platform) => {
                let numsArr = [];
                let sortArr = [];
                let allCount = 0;
                let MaxCount = 0;
                for (let key in platform) {
                    allCount += platform[key].task_count;
                    if(platform[key].task_count > MaxCount){
                        MaxCount = platform[key].task_count;
                    }
                }
                console.log((MaxCount / allCount) * 100)
                for (let key in platform) {
                    sortArr.push({
                        text: platform[key].name,
                        max:  100,
                    });
                }
                for (let key in platform) {
                    let radius = (platform[key].task_count / allCount)*100;
                    radius = radius.toFixed(2);
                    numsArr.push(radius);
                }
                return {
                    numsArr,
                    sortArr
                }
            }
            let slotObj = {
                // 充值相关
                'parseRecharge':  () => {
                    let { invest_money } = stayData.money;
                    let { weixin, zfb,admin } = invest_money;
                    weixin = Number(weixin);
                    zfb = Number(zfb);
                    admin = Number(admin)
                    let total = _self.formatePrice(weixin + zfb);
                    _self.investMoney = {
                        weixin: _self.formatePrice(weixin),
                        zfb: _self.formatePrice(zfb),
                        admin: _self.formatePrice(admin),
                        total: _self.formatePrice(weixin + zfb + admin)
                    }
                    _self.dynamicData.recharge.value = total;
                },
                // 提现  
                'withdraw': () => {
                     // 总提现
                    let withdrawTotal = _self.formatePrice(Number(stayData.money.pay_money.pay));
                    _self.dynamicData.withdraw.value = withdrawTotal;
                },
                // 盈利
                'earnings': () => {
                    let { cash_service_fee, platefrom_amount, index_income } = stayData.money.income;
                    let cashServiceFeePrice = Number(cash_service_fee.all_cash_service_fee);
                    let platefromAmountPrice = Number(platefrom_amount.platefrom_amount);
                    let indexIncomePrice = Number(index_income.index_income);
                    let total = cashServiceFeePrice + platefromAmountPrice + indexIncomePrice;
                    _self.dynamicData.earnings.value = _self.formatePrice(total);
                    _self.incomeMoney = {
                        stick: _self.formatePrice(indexIncomePrice),
                        cashServiceFee: _self.formatePrice(cashServiceFeePrice),
                        platefromAmount: _self.formatePrice(platefromAmountPrice),
                        total: _self.formatePrice(total),
                    }
                },
                // 支出
                'expand': () => {
                    let { user_inviter,user_be_inviter,
                            user_inviter_range,user_inviter_commission,
                            user_compile_task_rewarde,user_score_amount,
                            amount_all
                        } = stayData.money.all_pay;
                    _self.expendMoneu = {
                        invite: _self.formatePrice(user_inviter.all_pay),
                        beInvite: _self.formatePrice(user_be_inviter.all_pay),
                        inviteRange:  _self.formatePrice(user_inviter_range.all_pay),
                        commission:  _self.formatePrice(user_inviter_commission.all_pay),
                        taskRewarde:  _self.formatePrice(user_compile_task_rewarde.all_pay),
                        scoreAmout:  _self.formatePrice(user_score_amount.all_pay),
                        total:  _self.formatePrice(amount_all)
                    };
                },
                // 注册人数
                'regNums': () => {
                    let { register } = stayData.user;
                    let { male, female, unknown } = register;
                    male = male || 0;
                    female = female || 0;
                    unknown = unknown || 0;
                    let total = male + female + unknown;
                    let sexArr = [
                        {value: male,name: '男性',radius: male/total * 100}, 
                        {value: female,name: '女性',radius: female/total * 100}, 
                        {value: unknown,name: '未知',radius: unknown/total * 100}
                    ]
                    _self.dynamicData.register.value = total;
                    _self.sexOptions.series[0].data = sexArr;
                    _self.sexMap.setOption(_self.sexOptions);
                }, 
                // 比例相关
                'contrast': () => {
                    if (JSON.stringify(spec.rate) === '{}') {
                        _self.dynamicData.recharge.contrast = 0 + '%';
                        _self.dynamicData.withdraw.contrast = 0 + '%';
                        _self.dynamicData.earnings.contrast = 0 + '%';
                        _self.dynamicData.register.contrast = 0 + '%';
                        return;
                    }
                    let { income_rate,cash_rate,rachrge_rate,register_rate } = spec.rate;
                    
                    //income_rate = income_rate || 0;
                    //income_rate = income_rate > 0 ? '+' + income_rate : income_rate;
                    income_rate = parseFloat((income_rate * 100).toFixed(2));
                    income_rate = income_rate > 0 ? `+${income_rate}%`: `${income_rate}%`;

                    //cash_rate = cash_rate || 0;
                    //cash_rate = cash_rate > 0 ? '+' + cash_rate : cash_rate;
                    cash_rate = parseFloat((cash_rate * 100).toFixed(2));
                    cash_rate = cash_rate > 0 ? `+${cash_rate}%`: `${cash_rate}%`;

                    //rachrge_rate = rachrge_rate || 0;
                    //rachrge_rate = rachrge_rate > 0 ? '+' + rachrge_rate : rachrge_rate;
                    rachrge_rate = parseFloat((rachrge_rate * 100).toFixed(2));
                    rachrge_rate = rachrge_rate > 0 ? `+${rachrge_rate}%`: `${rachrge_rate}%`;

                    //register_rate = register_rate || 0;
                    //register_rate = register_rate > 0 ? '+' + register_rate : register_rate;
                    register_rate = parseFloat((register_rate * 100).toFixed(2));
                    register_rate = register_rate > 0 ? `+${register_rate}%`: `${register_rate}%`;

                    _self.dynamicData.recharge.contrast = rachrge_rate;
                    _self.dynamicData.withdraw.contrast = cash_rate;
                    _self.dynamicData.earnings.contrast = income_rate;
                    _self.dynamicData.register.contrast = register_rate;
                },
                // 榜单
                'rank': () => {
                    let tableData = [];
                    let {   drown_most,recharge_most,
                            inviter_most,
                            accept_task_most,publish_task_most } = spec.most;
                    if (publish_task_most.count) {
                        tableData.push({
                            reason: 1,
                            count: publish_task_most.count,
                            avatar: publish_task_most.user.avatar,
                            nick: publish_task_most.user.nick_name
                        });
                    }
                    if (accept_task_most.count) {
                        tableData.push({
                            reason: 2,
                            count: accept_task_most.count,
                            avatar: accept_task_most.user.avatar,
                            nick: accept_task_most.user.nick_name
                        });
                    }
                    if (recharge_most.count) {
                        tableData.push({
                            reason: 3,
                            count: _self.formatePrice(recharge_most.count),
                            avatar: recharge_most.user.avatar,
                            nick: recharge_most.user.nick_name
                        });
                    }
                    if (drown_most.count) {
                        tableData.push({
                            reason: 4,
                            count: _self.formatePrice(drown_most.count),
                            avatar: drown_most.user.avatar,
                            nick: drown_most.user.nick_name
                        });
                    }
                    if (inviter_most.count) {
                        tableData.push({
                            reason: 5,
                            count: inviter_most.count,
                            avatar: inviter_most.user.avatar,
                            nick: inviter_most.user.nick_name
                        });
                    }

                    _self.tableData = tableData;
                },
                // 用户分布
                'userDistribution': () => {
                    let curName = _self.type.list[_self.type.index];
                    let { register } = stayData.user;
                    let { male, female, unknown } = register;
                    let total = male + female + unknown;
                    if (JSON.stringify(spec.location) === '{}') {
                        _self.tableData = [];
                        return;
                    }
                    let lcList = [];
                    let max = 0;
                    for (let key in spec.location) {
                        lcList.push({
                            name: key,
                            value: spec.location[key],
                            radius:  Number(spec.location[key] / total * 100).toFixed(2)
                        })
                        if(spec.location[key]>max){
                            max = spec.location[key];
                        }
                    }
                    
                    console.log(lcList);
                    _self.userEarthOptions.title.text = curName + "用户分布";
                    _self.userEarthOptions.visualMap.max = max;
                    if(max==0){
                        _self.userEarthOptions.visualMap.inRange.color = ['#F1F1F1'];
                    }else{
                        _self.userEarthOptions.visualMap.inRange.color = [
                            'rgba(158, 207, 102,0.2)',
                            'rgba(158, 207, 102,0.4)',
                            'rgba(158, 207, 102,0.6)',
                            'rgba(158, 207, 102,0.8)', 
                            'rgba(158, 207, 102,1)'
                        ];
                    }
                    _self.userEarthOptions.series[0].data = lcList;
                    _self.userEarthMap.setOption(_self.userEarthOptions);
                },
                'taskSort': () => {
                    let curName = _self.type.list[_self.type.index];
                    let stayUse = parseSingle(stayData.task.platform);
                    if (stayUse.sortArr.length <= 0 ) {
                        return;
                    }
                    _self.pushTaskSortOptions.title.text = curName + "分类趋势";
                    _self.pushTaskSortOptions.legend.data[0] = curName;
                    _self.pushTaskSortOptions.radar[0].indicator = stayUse.sortArr;
                    _self.pushTaskSortOptions.series[0].data[0].name = curName;
                    _self.pushTaskSortOptions.series[0].data[0].value = stayUse.numsArr;
                    _self.pushTaskSortMap.setOption(_self.pushTaskSortOptions);
                },
                // 任务完成读
                'taskComplate': () => {
                    let  { complete,publish} = stayData.task.platfrom_project_compilted;
                    let  complateList = [];
                    let tempObj = {};
                    let sortTemp = {};
                    let taskCompletePriceTotal = 0;
                    for (let sorta=0;sorta < publish.length;sorta++) {
                        let sortaItem = publish[sorta];
                        // 分类基本信息
                        tempObj = {
                            name: sortaItem.name,
                            id: sortaItem.id,
                            icon: sortaItem.icon,
                            totalCount: {
                                publish: sortaItem.count,
                                complete: 0
                            },
                            totalPrice: {
                                publish:  _self.formatePrice(sortaItem.amount),
                                complete: 0
                            },
                            branchList: []
                        }
                        for (let sortb=0;sortb<complete.length;sortb++) {
                            let sortbItem = complete[sortb];
                            if (sortaItem.id == sortbItem.id) {
                                taskCompletePriceTotal += sortbItem.amount;
                                tempObj.totalCount.complete = sortbItem.count;
                                tempObj.totalPrice.complete = _self.formatePrice(sortbItem.amount);
                                for (let sortc =0;sortc<sortaItem.project.length;sortc++) {
                                    let sortcItem = sortaItem.project[sortc];
                                    sortTemp= {
                                        name: sortcItem.name,
                                        id: sortcItem.id,
                                        icon: sortcItem.icon,
                                        totalCount: {
                                            publish: sortcItem.count,
                                            complete: 0
                                        },
                                        totalPrice: {
                                            publish:  _self.formatePrice(sortcItem.amount),
                                            complete: 0
                                        },
                                    }
                                    for (let sortd=0;sortd<sortbItem.project.length;sortd++) {
                                        let sortdItem = sortbItem.project[sortd];
                                        if (sortcItem.id == sortdItem.id) {
                                            sortTemp.totalCount.complete = sortdItem.count;
                                            sortTemp.totalPrice.complete = _self.formatePrice(sortdItem.amount);
                                            tempObj.branchList.push(sortTemp);
                                            continue;
                                        }
                                    }
                                }
                                complateList.push(tempObj);
                                continue;
                            }
                        }
                    }
                    _self.taskCompleteList = complateList;
                    _self.taskCompletePriceTotal = _self.formatePrice(taskCompletePriceTotal);
                }
            };
            slotObj['parseRecharge']();
            slotObj['withdraw']();
            slotObj['earnings']();
            slotObj['expand']();
            slotObj['regNums']();
            slotObj['contrast']();
            slotObj['rank']();
            slotObj['userDistribution']();
            slotObj['taskComplate']();
            slotObj['taskSort']();
        },
        /**
         *  获取最近日期充值提现
         */
        getRechangKitLately() {
            const DIFFER_DAYS = 14;
            let todayDate = new Date();
            const calculateDate = (diffDay) => {
                    // 毫秒数
                let prevMills = diffDay * 24 * 60 * 60 * 1000;
                let curMills = todayDate.getTime();
                return new Date(curMills - prevMills);
            };
            const parseRecharge = (singleObj) => {
                let { invest_money } = singleObj.money;
                let { weixin,zfb } = invest_money;
                weixin = Number(weixin);
                zfb = Number(zfb);
                return _self.formatePrice(weixin + zfb);
            }
            let startDate = calculateDate(DIFFER_DAYS);

            let days = [];
            for (let dayIndex= DIFFER_DAYS ; dayIndex >= 0;dayIndex-- ) {
                let curDay = calculateDate(dayIndex);
                days.push(uilts.Dateformat(curDay,"M-d"));
            }
            this.rechangKitOptions.xAxis.data = days;
            this.pushTaskPriceOptions.xAxis.data = days;
            let _self = this;
            this.getStatisticsDataApi({
                query_time: 'other',
                start: uilts.Dateformat(startDate,'yyyy-MM-dd'),
                end: uilts.Dateformat(todayDate,'yyyy-MM-dd'),
                day: 1, 
            },(res)=>{
                console.log(res);
                let rechargeTotalArr = [];
                let withdrawTotalArr = [];
                let pushPriceTotalArr = [];

                if(res.length <= 0 ) {
                    return;
                }
                for (let i =0;i<res.length;i++) {
                    // 总充值
                    let rechargeTotal = parseRecharge(res[i]);
                    rechargeTotalArr.push(rechargeTotal);
                    // 总提现
                    let withdrawTotal = _self.formatePrice(Number(res[i].money.pay_money.pay));
                    withdrawTotalArr.push(withdrawTotal);
                     // 总发布金额
                    let pushPriceTotal = 0;
                    res[i].task.platform.map((platItem)=>{
                        pushPriceTotal += Number(platItem.amount);
                    })
                    pushPriceTotal = _self.formatePrice(pushPriceTotal);
                    pushPriceTotalArr.push(pushPriceTotal);

                }

                _self.rechangKitOptions.series[0].data = withdrawTotalArr;
                _self.rechangKitOptions.series[1].data = rechargeTotalArr;
                _self.pushTaskPriceOptions.series[0].data = pushPriceTotalArr;

                _self.rechangKitMap.setOption(_self.rechangKitOptions);
                _self.pushTaskPriceMap.setOption(_self.pushTaskPriceOptions);
            });
        },
        formatePrice (stayPrice)  {
            let ratio = 10000;
            return String(parseFloat((stayPrice/ratio).toFixed(3)));
        },
        getStatisticsDataApi(resPar,callBack) {
            resPar.load = true;
            this.comResquest(this.request.getDataCount,(res)=>{
                callBack(res.info || res);
            },resPar);
        },
        handleSpecData() {
            let _self = this;
            const parseSingle = (stayData) => {
                let { platform } = stayData.task;
                let numsArr = [];
                let sortArr = [];
                let allCount = 0;
                let MaxCount = 0;
                for (let key in platform) {
                    allCount += platform[key].task_count;
                    if(platform[key].task_count > MaxCount){
                        MaxCount = platform[key].task_count;
                    }
                }
                console.log((MaxCount / allCount) * 100)
                for (let key in platform) {
                    sortArr.push({
                        text: platform[key].name,
                        max:  (MaxCount / allCount) * 100,
                    });
                }
                for (let key in platform) {
                    let radius = (platform[key].task_count / allCount)*100;
                    radius = radius.toFixed(2);
                    numsArr.push(radius);
                }
                return {
                    numsArr,
                    sortArr
                }
            }
            const parseSort =  (yesterday,today,all) => {
                let yesObj = parseSingle(yesterday.this_vcation);
                let toObj = parseSingle(today.this_vcation);
                let allObj = parseSingle(all.this_vcation);

                console.log(yesObj);

                _self.pushTaskSortOptions.radar[0].indicator = yesObj.sortArr;

                _self.pushTaskSortOptions.series[0].data[0].value = yesObj.numsArr;
                _self.pushTaskSortOptions.series[0].data[1].value = toObj.numsArr;
                _self.pushTaskSortOptions.series[0].data[2].value = allObj.numsArr;

                _self.pushTaskSortMap.setOption(_self.pushTaskSortOptions);
            };
            this.getStatisticsDataApi({get_data: 1},(res)=>{
                let { all,yesterday,today } = res;
                _self.textTotal = all.this_vcation.text_decriber;
                _self.todayTextTotal = today.this_vcation.text_decriber;
                _self.parseData(today.this_vcation,today.analysis);
                let { money,user } = all.this_vcation;
                _self.awiatMoneyTotal = _self.formatePrice(money.all_wait_money);
                // 新用户行为标签列表
                //newUserTagsList: [],
                // 老用户行为标签列表
                //oldUserTagsList: []
                _self.newUserTagsList = user.new_user_text_analysis;
                _self.oldUserTagsList = user.old_user_text_analysis;
            });
        }
    },
    components: {
        HeadTotal
    }
}